package org.l.qiao.web;

import org.l.qiao.Cluster;
import org.l.qiao.KeyType;
import org.l.qiao.LBean;
import org.l.qiao.Validate;
import org.l.qiao.annotation.Key;
import org.l.qiao.base.Convert;
import org.l.qiao.base.LType;
import org.l.qiao.util.ClusterUtil;

import java.util.Map;

/**
 * Created by 严秋旺 on 2015/1/18.
 */
public class KeyUpdate extends LBean {

    private Map<String, Key> keys;

    /**
     * id
     */
    @Key(keyType = KeyType.PropertyKey, valueType = LType.LTYPE_STRING, check = "")
    private String id;

    /**
     * 键名
     */
    @Key(keyType = KeyType.PropertyKey, valueType = LType.LTYPE_STRING, check = "^\\w{1,20}$")
    private String name;

    /**
     * 值
     */
    @Key(keyType = KeyType.PropertyKey, valueType = LType.LTYPE_STRING, check = "")
    private String value;


    public KeyUpdate(Class clazz) {
        keys = ClusterUtil.keys(clazz);
    }

    public Map<String, Key> getKeys() {
        return keys;
    }

    public void setKeys(Map<String, Key> keys) {
        this.keys = keys;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    /**
     * 获取键名
     *
     * @return
     */
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取值
     *
     * @return 返回原始值
     */
    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    /**
     * ID转换
     */
    public Object parseId() {
        Key idKey = keys.get(Cluster.ID);
        return Convert.parse(idKey, id);
    }

    /**
     * 值转换
     *
     * @return 转换的值对象
     * @throws Exception
     */
    public Object parseValue() {
        Key nameKey = keys.get(name);
        return Convert.parse(nameKey, value);
    }

    /**
     * 验证原始值
     *
     * @return
     */
    public boolean check() {
        boolean checkResult = true;
        Key idKey = keys.get(Cluster.ID);
        checkResult = Validate.check(idKey.check(), id);
        checkResult = checkResult && !Cluster.ID.equals(name) && keys.containsKey(name) && Validate.check("^\\w{1,20}$", name);

        if (checkResult) {
            Key nameKey = keys.get(name);
            checkResult = checkResult && Validate.check(nameKey.check(), value);
        }

        return checkResult;
    }
}
